package service

import (
	"reflect"
	"remoteGo/remote/coder"
	"remoteGo/remote/io"
)

type ChanSendProxy struct {
	cp       ChanProxy
	socket   io.Socket
	chanVal  reflect.Value
	stopChan chan any
}

type ChanRecvProxy struct {
	cp ChanProxy
	//socket   io.Socket
	chanVal  reflect.Value
	stopChan chan any
}

type ChanMessage struct {
	Proxy   ChanProxy
	Message interface{}
	Closed  bool
}

//func (c *ChanRecvProxy) Listen() {
//	go func() {
//		for true {
//			select {
//			case <-c.stopChan:
//				c.socket.Close()
//				return
//			default:
//				var r ChanMessage
//				err := c.socket.Recv(&r)
//				fmt.Println(r)
//				if err != nil {
//					panic(err)
//				}
//				c.chanVal.Send(reflect.ValueOf(r.Message))
//			}
//		}
//	}()
//}

func (c *ChanRecvProxy) Stop() {
	c.stopChan <- nil
}

func (c *ChanSendProxy) Redirect() {
	go func() {
		for true {
			select {
			case <-c.stopChan:
				c.socket.Close()
				return
			default:
				message, ok := c.chanVal.Recv()
				//fmt.Println(message, ok)
				if ok {
					err := c.socket.Send(ChanMessage{
						Message: message.Interface(),
						Proxy:   c.cp,
					})
					if err != nil {
						//TODO: handle error
						panic(err)
					}
				} else {
					err := c.socket.Send(ChanMessage{
						Closed: true,
						Proxy:  c.cp,
					})
					if err != nil {
						//TODO: handle error
						panic(err)
					}
				}
			}
		}
	}()
	return
}

func init() {
	coder.GetGobCoder().Register(ChanMessage{})
}
